﻿using EventHandlerDemo.Domain.Bases;
using Microsoft.EntityFrameworkCore.Storage;

namespace EventHandlerDemo.Infrastructure.EFCore
{
    public class EFCoreUnitOfWork : IUnitOfWork
    {
        private readonly AppDbContext _dbContext;
        protected IDbContextTransaction? DbContextTransaction { get; set; }

        public EFCoreUnitOfWork(AppDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public void BeginTransaction()
        {
            DbContextTransaction = _dbContext.Database.BeginTransaction();
        }

        public int Commit()
        {
            var result = _dbContext.SaveChanges();
            DbContextTransaction.Commit();
            return result;
        }

        public async Task<int> CommitAsync(CancellationToken cancellationToken = default)
        {
            var result = await _dbContext.SaveChangesAsync(cancellationToken);
            await DbContextTransaction.CommitAsync(cancellationToken);
            return result;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (DbContextTransaction is not null)
                {
                    DbContextTransaction.Dispose();
                    DbContextTransaction = null;
                }
            }
        }

        public void Rollback()
        {
            DbContextTransaction.Rollback();
        }

        public async Task RollbackAsync()
        {
            await DbContextTransaction.RollbackAsync();
        }

        public async Task<int> SaveChangeAsync(CancellationToken cancellationToken = default)
        {
            var result = await _dbContext.SaveChangesAsync(cancellationToken);
            return result;
        }
    }
}
